/* 
 * 
 * Copyright (c) 2007 John Wells
 * Copyright (c) 2010 Photonic Games

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;


namespace GameLevel.ContentPipeline.Leadwerks14
{
    public sealed class BrushFace
    {
        #region Fields
        // Public fields
        public FaceFlags Flags;
        public Plane TextureMappingUPlane, TextureMappingVPlane;
        public Vector2 TexturePosition, TextureScale, TextureRotation;
        public float LuxelSize;
        public int SmoothingGroupIndex, MaterialIndex;
        public int? LightmapIndex;
        public Vector2[] TextureCoordinates, LightmapTextureCoordinates;
        public int[] VertexIndices;
        public Brush Brush;
        public Material Material;
        public String Name;

        // Public fields used by the processor code
        public Plane Plane;
        public SurfaceDocument Surface;
        public List<BrushVertex> Vertices = new List<BrushVertex>();

        // Enumerations
        [Flags]
        public enum FaceFlags
        {
            None = 0,
            Hidden = 4,
            IncludesLightmap = 16
        }
        #endregion

        public BrushFace(BinaryReader reader, Brush brush, Vector3[] vertices)
        {
            // Read the face flags
            this.Flags = (FaceFlags)reader.ReadByte();

            // Read the attribute data
            this.Plane = Leadwerks14Importer.ReadPlane(reader);
            this.TexturePosition = Leadwerks14Importer.ReadVector2(reader);
            this.TextureScale = Leadwerks14Importer.ReadVector2(reader);
            this.TextureRotation = Leadwerks14Importer.ReadVector2(reader);
            this.TextureMappingUPlane = Leadwerks14Importer.ReadPlane(reader);
            this.TextureMappingVPlane = Leadwerks14Importer.ReadPlane(reader);
            this.LuxelSize = reader.ReadSingle();
            this.SmoothingGroupIndex = reader.ReadInt32();
            this.MaterialIndex = reader.ReadInt32() - 1;

            // Optionally read the lightmap index
            if ((this.Flags & FaceFlags.IncludesLightmap) == FaceFlags.IncludesLightmap)
                this.LightmapIndex = reader.ReadInt32();
            else
                this.LightmapIndex = null;

            // Read the per-vertex information for this face
            this.VertexIndices = new int[reader.ReadByte()];
            this.TextureCoordinates = new Vector2[this.VertexIndices.Length];
            this.LightmapTextureCoordinates = new Vector2[this.VertexIndices.Length];
            for (int index = 0; index < this.VertexIndices.Length; index++)
            {
                // Always read the vertex index and tex coord
                this.VertexIndices[index] = reader.ReadByte();
                this.TextureCoordinates[index] = Leadwerks14Importer.ReadVector2(reader);

                // Optionally read the lightmap tex coords
                if ((this.Flags & FaceFlags.IncludesLightmap) == FaceFlags.IncludesLightmap)
                    this.LightmapTextureCoordinates[index] = Leadwerks14Importer.ReadVector2(reader);
                else this.LightmapTextureCoordinates[index] = Vector2.Zero;
            }

            Array.Reverse(this.VertexIndices);
            Array.Reverse(this.TextureCoordinates);
            Array.Reverse(this.LightmapTextureCoordinates);

           // System.Diagnostics.Debugger.Launch();

            // Store a reference to the brush this face belongs to
            this.Brush = brush;

            //System.Diagnostics.Debugger.Launch();

            // Create the vertices
            for (int index = 0; index < this.VertexIndices.Length; index++)
            {
                int vertexIndex = this.VertexIndices[index];

                // Build the base parts of this vertex
                Vector3 position = vertices[vertexIndex];
                Vector2 textureCoordinate = this.TextureCoordinates[index];
                Vector3 normal = this.Plane.Normal; //  Vector3.Up; //  new Vector3(this.Plane.Normal.X, this.Plane.Normal.Y, this.Plane.Normal.Z * -1);
                //normal += new Vector3(0.1f, 0.1f, 0.1f);
                normal.Normalize();

                Vector3 TextureMappingUPlane = this.TextureMappingUPlane.Normal; //  new Vector3(this.TextureMappingUPlane.Normal.X, this.TextureMappingUPlane.Normal.Y, this.TextureMappingUPlane.Normal.Z);
                Vector3 TextureMappingVPlane = this.TextureMappingVPlane.Normal; // new Vector3(this.TextureMappingVPlane.Normal.X, this.TextureMappingVPlane.Normal.Y, this.TextureMappingVPlane.Normal.Z);
                Vector3 binormal = Vector3.Cross(TextureMappingUPlane, TextureMappingVPlane);
                Vector3 tangent = Vector3.Cross(normal, binormal);
                Vector2 lightmapCoordinate = this.LightmapTextureCoordinates[index];

                // This value starts off at 0 because we don't have all faces at this time - As a later step you must go
                // back and compare using all faces and some configurable settings (in my implementation this is done in
                // the Leadwerks14LevelProcessor class)
                float ambientOcclusion = 0.0f;

                
                BrushVertex vertex = new BrushVertex(position, textureCoordinate, normal, binormal, tangent, ambientOcclusion, lightmapCoordinate);
                this.Vertices.Add(vertex);
            }
        }
    }
}
